//
//  LoginMenuViewModel.swift
//  SwiftSign
//
//  Created by continue on 2021/5/14.
//

import UIKit
import RxSwift
import RxCocoa

class LoginMenuViewModel: ViewModel, ViewModelType {
   
    struct Input {
        let fastLoginTrigger: Driver<Void>
        let phoneLoginTrigger: Driver<Void>
    }
    
    struct Output {
        let phoneLoginSelected: Driver<PhoneLoginViewModel>
    }
    
    let randUserInfo = PublishSubject<RandUserInfo>()
    var phoneLoginSelected = PublishSubject<PhoneLoginViewModel>()
    
    func transform(input: Input) -> Output {
        
        input.phoneLoginTrigger.drive(onNext: { [weak self] () in
            guard let provider = self?.provider, let initInfo = self?.initInfo else { return }
            let viewModel = PhoneLoginViewModel(provider: provider, initInfo)
            self?.phoneLoginSelected.onNext(viewModel)
        }).disposed(by: rx.disposeBag)
        
        input.fastLoginTrigger.asObservable().flatMap { _ in
            return self.provider.getRandUser()
                .trackActivity(self.loading)
                .trackError(self.error)
        }.subscribe({ [weak self] (event) in
            switch event {
            case .next(let data):
                self?.randUserInfo.onNext(data)
            case .error(let error):
                LogError(error.localizedDescription)
            default: break
            }
        }).disposed(by: rx.disposeBag)
        
        randUserInfo.flatMapLatest { (user) -> Observable<Event<UserInfo>>  in
            let username = user.username ?? ""
            let password = user.password ?? ""
            return self.provider.userRegister(username:username, password:password)
                .trackActivity(self.loading)
                .trackError(self.error)
                .materialize()
        }.subscribe(onNext: { (event) in
            switch event {
            case .next(let user):
                LogInfo(user.toJSONString())
            case .error(let error):
                LogError(error.localizedDescription)
            default: break
            }
        }).disposed(by: rx.disposeBag)
        
        return Output(phoneLoginSelected: phoneLoginSelected.asDriverOnErrorJustComplete())
    }
}
